package com.ibuonline.search.solr.loader;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ibuonline.utils.DbUtils;

public abstract class AbstractDbLoader implements DataLoader {
	private static final Logger log = LoggerFactory
			.getLogger(AbstractDbLoader.class);
	protected DataSource dataSource;

	/**
	 * 加载数据
	 */
	public void load() {
		log.info("开始加载" + getJobName() + "数据...");
		Connection conn = null;
		Statement stmt = null;
		ResultSet rs = null;
		try {
			conn = dataSource.getConnection();
			stmt = conn.createStatement();
			rs = stmt.executeQuery(getSql());
			proecessResultSet(rs);
			log.info("加载" + getJobName() + "数据已完成。");
		} catch (SQLException e) {
			log.error("开始加载" + getJobName() + "数据异常", e);
		} finally {
			DbUtils.close(conn, stmt, rs);
		}
		
	}

	protected abstract String getSql();

	protected abstract void proecessResultSet(ResultSet rs) throws SQLException;

	protected abstract String getJobName();

	/**
	 * @param dataSource
	 *            the dataSource to set
	 */
	public void setDataSource(DataSource dataSource) {
		this.dataSource = dataSource;
	}
}